import { Column } from '@antv/g2plot'
import { get } from 'lodash'
import { useEffect, useLayoutEffect, useRef, useState } from 'react'

import styles from './reservoirInventory.module.less'
import { getRemFontSize } from './stockNumber'

const LEVEL_MAP = { 1: '一楼', 2: '二楼' }
const TYPE_MAP = { 1: '大烫', 2: '复查', 3: '包装' }

export default (props) => {
  const { data } = props

  const containerRef = useRef<any>()

  const [cHeight, setCHeight] = useState(0)
  const [chart, setChart] = useState<null | Column>()

  // 库存量
  useEffect(() => {
    // if (data && data.length) {
    const columnPlot = new Column('inventory', {
      data: [],
      isStack: true,
      xField: 'area',
      yField: 'value',
      seriesField: 'type',
      autoFit: true,
      label: null,
      height: cHeight * 0.8,
      color: (value) => {
        if (value.type === 'Total') {
          return '#072C88'
        }
        if (value.type === 'Full') {
          return '#DD2A2A'
        }
        if (value.type === 'Large') {
          return '#F7B500'
        }
        return '#0EC5DF'
      },
      legend: false,
      tooltip: false,
      xAxis: {
        label: {
          autoHide: true,
          autoRotate: false,
          style: {
            lineHeight: 20,
            fontSize: 12,
            fill: '#FFFFFF'
          }
        },
        tickLine: null
      },
      yAxis: {
        range: [0, 0.86],
        title: {
          text: '件数',
          autoRotate: false,
          position: 'end',
          offset: 10,
          style: {
            fontSize: 12,
            fill: '#FFFFFF'
          }
        },
        label: {
          style: {
            fontSize: 12,
            fill: '#FFFFFF'
          }
        },
        grid: {
          line: {
            style: {
              lineWidth: 1,
              lineDash: [2, 5]
            }
          }
        }
      },
      maxColumnWidth: 48,
      // minColumnWidth: 48,
      annotations: []
    })
    columnPlot.render()
    setChart(columnPlot)
    // }
  }, [])

  useEffect(() => {
    if (chart) {
      const barData = []
      data.forEach((item) => {
        barData.push({
          area:
            item.areaFunctionType === 1 || item.areaFunctionType === 2
              ? `${get(TYPE_MAP, item.areaFunctionType)}${get(
                  LEVEL_MAP,
                  item.areaLevel
                )}`
              : `${get(TYPE_MAP, item.areaFunctionType)}`,
          value:
            item.areaCapacity - item.areaStockAmount < 0
              ? 0
              : item.areaCapacity - item.areaStockAmount,
          capacity: item.areaCapacity,
          type: 'Total'
        })
      })

      data.forEach((item) => {
        barData.push({
          area:
            item.areaFunctionType === 1 || item.areaFunctionType === 2
              ? `${get(TYPE_MAP, item.areaFunctionType)}${get(
                  LEVEL_MAP,
                  item.areaLevel
                )}`
              : `${get(TYPE_MAP, item.areaFunctionType)}`,
          value: item.areaStockAmount,
          type: 'Basic'
        })
      })

      const annotations = []

      const arr = barData.filter((item) => item.type === 'Total')
      arr.forEach((item, k) => {
        const target = barData.find(
          (i) =>
            i.area === item.area && ['Basic', 'Full', 'Large'].includes(i.type)
        )
        const position =
          item.value + target.value < target.value
            ? target.value
            : item.value + target.value
        annotations.push({
          type: 'text',
          position: [k, position],
          content: `${item.capacity}`,
          style: { textAlign: 'center', fontSize: 14, fill: '#fff' },
          offsetY: -20
        })
      })

      const arr2 = barData.filter((item) =>
        ['Basic', 'Full', 'Large'].includes(item.type)
      )
      arr2.forEach((item, k) => {
        const target = barData.find(
          (i) => i.area === item.area && ['Total'].includes(i.type)
        )
        const realTotal = item.value + target.value
        const position =
          Math.floor(item.value / 2) < 1 ? 1 : Math.floor(item.value / 2)

        annotations.push({
          type: 'text',
          position: [k, position],
          content: `${item.value}\n${Number(
            ((item.value / realTotal) * 100).toFixed(0)
          )}% `,
          style: { textAlign: 'center', fontSize: 14, fill: '#fff' },
          offsetY: position % 2 === 1 ? -10 : 0
        })
      })
      chart.update({
        data: barData,
        annotations
      })
    }
  }, [chart, data])

  useLayoutEffect(() => {
    if (containerRef.current) {
      const containerHeight = containerRef.current.clientHeight
      setCHeight(containerHeight)
    }
  }, [])

  useEffect(() => {
    window.addEventListener('resize', resize)
    resize() // 初始化

    return () => {
      window.removeEventListener('resize', resize)
    }
  }, [chart, data])

  const resize = () => {
    if (!chart) return
    const barData = []
    data.forEach((item) => {
      barData.push({
        area:
          item.areaFunctionType === 1 || item.areaFunctionType === 2
            ? `${get(TYPE_MAP, item.areaFunctionType)}${get(
                LEVEL_MAP,
                item.areaLevel
              )}`
            : `${get(TYPE_MAP, item.areaFunctionType)}`,
        value:
          item.areaCapacity - item.areaStockAmount < 0
            ? 0
            : item.areaCapacity - item.areaStockAmount,
        capacity: item.areaCapacity,
        type: 'Total'
      })
    })

    data.forEach((item) => {
      barData.push({
        area:
          item.areaFunctionType === 1 || item.areaFunctionType === 2
            ? `${get(TYPE_MAP, item.areaFunctionType)}${get(
                LEVEL_MAP,
                item.areaLevel
              )}`
            : `${get(TYPE_MAP, item.areaFunctionType)}`,
        value: item.areaStockAmount,
        type: 'Basic'
      })
    })

    const annotations = []

    const arr = barData.filter((item) => item.type === 'Total')
    arr.forEach((item, k) => {
      const target = barData.find(
        (i) =>
          i.area === item.area && ['Basic', 'Full', 'Large'].includes(i.type)
      )
      const position =
        item.value + target.value < target.value
          ? target.value
          : item.value + target.value
      annotations.push({
        type: 'text',
        position: [k, position],
        content: `${item.capacity}`,
        style: {
          textAlign: 'center',
          fontSize: getRemFontSize() * 1,
          fill: '#fff'
        },
        offsetY: -20
      })
    })

    const arr2 = barData.filter((item) =>
      ['Basic', 'Full', 'Large'].includes(item.type)
    )
    arr2.forEach((item, k) => {
      const target = barData.find(
        (i) => i.area === item.area && ['Total'].includes(i.type)
      )
      const realTotal = item.value + target.value
      const position =
        Math.floor(item.value / 2) < 1 ? 1 : Math.floor(item.value / 2)

      annotations.push({
        type: 'text',
        position: [k, position],
        // content: `${item.value}\n${Number(
        //   ((item.value / realTotal) * 100).toFixed(0)
        // )}% `,
        content: `${item.value}`,
        style: {
          textAlign: 'center',
          fontSize: getRemFontSize() * 1,
          fill: '#fff'
        },
        offsetY: position % 2 === 1 ? -10 : 0
      })
    })

    chart.update({
      // label: {
      //   style: {
      //     fontSize: getRemFontSize() * 1,
      //     fill: '#FFF'
      //   }
      // },
      xAxis: {
        label: {
          style: {
            fontSize: getRemFontSize() * 1,
            lineHeight: getRemFontSize() * 1.45
          }
        }
      },
      yAxis: {
        label: {
          style: {
            fontSize: getRemFontSize() * 1.25
          }
        },
        title: {
          style: {
            fontSize: getRemFontSize() * 1.25
          }
        }
      },
      maxColumnWidth: getRemFontSize() * 3,
      annotations
    })
  }

  return (
    <div className={styles.container} ref={containerRef}>
      <header className={styles.inventoryHeader}>库区库存量</header>
      <div id="inventory" className={styles.inventoryBox} />
    </div>
  )
}
